import csv
import os.path

from .student import Student


class StudentManager:
    """学员管理类"""

    # 学员列表存储学员信息
    students = []
    dirname = os.path.dirname(__file__)
    filename = os.path.join(dirname, 'students.csv')

    def __init__(self):
        self._init_students()

    def _init_students(self):
        """加载学员信息"""
        try:
            f = open(self.filename, encoding='utf-8')
            try:
                reader = csv.DictReader(f)
                self.students.extend(Student(**row) for row in reader)
            except Exception as e:
                print(e)
            finally:
                f.close()
        except FileNotFoundError:
            pass

    def run(self):
        """程序入口"""
        while True:
            self.show_menu()

            try:
                menu_num = int(input('请输入功能序号：'))
            except ValueError:
                print('输入有误，请重新输入1~6之间的任意数字')
                continue

            if menu_num == 1:
                self.add_student()
            elif menu_num == 2:
                self.del_student()
            elif menu_num == 3:
                self.mod_student()
            elif menu_num == 4:
                self.list_student()
            elif menu_num == 5:
                self.show_all_student()
            elif menu_num == 6:  # 退出系统
                break

        self.write2json()

    @staticmethod
    def show_menu():
        """显示功能菜单"""
        print('-' * 15)
        print('请选择如下功能')
        print('1:添加学员信息')
        print('2:删除学员信息')
        print('3:修改学员信息')
        print('4:查询学员信息')
        print('5:显示所有学员信息')
        print('6:退出系统')
        print('-' * 15)

    def check_student_exist(self, name):
        """检查学员是否存在"""
        for student in self.students:
            if student.name.lower() == name.lower():
                return student

        return None

    def add_student(self):
        """添加学员信息"""
        # 1. 用户输入姓名、性别和手机号
        name = input('请输入学员的姓名：')
        student = self.check_student_exist(name)
        if student:
            print(f'该学员已存在！')
            return

        gender = input('请输入学员的性别：')
        tel = input('请输学员的手机号：')

        # 2. 创建学员对象
        student = Student(name.title(), gender, tel)

        # 3. 添加学员对象到学员列表
        self.students.append(student)

    def del_student(self):
        """删除学员信息"""
        name = input('请输入要删除的学员姓名：')
        student = self.check_student_exist(name)
        if not student:
            print('查无此人！')

        self.students.remove(student)

    def mod_student(self):
        """修改学员信息"""
        name = input('请输入要修改的学员姓名：')
        student = self.check_student_exist(name)
        if not student:
            print('查无此人！')
            return

        student.gender = input('请输入学员的性别：')
        student.tel = input('请输入学员的手机号：')
        print(f'修改学员信息成功！')

    def list_student(self):
        """查询学员信息"""
        name = input('请输入要查询的学员的姓名：')
        student = self.check_student_exist(name)
        if not student:
            print('查无此人！')
            return

        print(student)

    def show_all_student(self):
        """显示所有学员信息"""
        if not self.students:
            print('学员管理系统还没有录入学员')

        for student in self.students:
            print(student)

    def write2json(self):
        """保存学员信息"""
        with open(self.filename, 'w', encoding='utf-8', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=['name', 'gender', 'tel'])
            writer.writeheader()
            writer.writerows(student.__dict__ for student in self.students)
